/*
 * Copyright © 2024-2025 Wenze Wei
 *
 * This file is part of StadionOS.
 *
 * This Source Code Form is subject to the terms of the GNU General Public License, v. 2.0.
 * You can obtain a copy of the GPL at
 * https://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 */

#include "../include/malloc.h"

/**
 * @brief Frees allocated memory.
 *
 * This function frees the memory block pointed to by 'ptr'.
 * It locks the mutex to ensure thread safety and then marks the block as free.
 * It also merges adjacent free blocks to reduce fragmentation.
 *
 * @param ptr A pointer to the memory block to be freed.
 */
void Sfree(void *ptr) {  
    if (!ptr)
        return;

    pthread_mutex_lock(&mutex);
    TBlock *block_to_free = (TBlock *)ptr - 1;

    block_to_free->free = 1;

    TBlock *current = head;
    while (current) {
        if (current->free) {
            if (current->next && current->next->free) {
                current->size += sizeof(TBlock) + current->next->size;
                current->next = current->next->next;
            } else {
                current = current->next;
            }
        } else {
            current = current->next;
        }
    }

    pthread_mutex_unlock(&mutex);
}